package com.elvish.oda.busin.dao;

import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.elvish.oda.busin.pojo.Permission;
import com.elvish.oda.common.dao.BaseDao;
import com.elvish.oda.common.utils.NutzSqlUtil;

@Component
public class PermissionDao extends BaseDao {

	@Autowired
	Dao dao;

	public List<Permission> findAll() {
		return NutzSqlUtil.getEntities(dao, Permission.class);
	}

	public Permission findById(Integer id) {
		return NutzSqlUtil.findById(dao, Permission.class, id);
	}

	public List<Permission> findByPid(Integer id) {
		String delSql = "select * from t_permission where pid = @pid";
		Sql sql = Sqls.fetchString(delSql);
		sql.setParam("pid", id);
		return NutzSqlUtil.getEntities(sql, dao, Permission.class);
	}

	public <T> int save(T obj) {
		return NutzSqlUtil.save(dao, obj);
	}

	public <T> int deleteById(Class<T> clz, Integer id) {
		return NutzSqlUtil.deleteById(dao, clz, id);
	}

	public int deleteByPid(Integer id) {
		String delSql = "delete from t_permission where pid = @pid";
		Sql sql = Sqls.fetchString(delSql);
		sql.setParam("pid", id);
		dao.execute(sql);
		return 1;
	}

	public <T> int update(T obj) {
		return dao.update(obj);
	}

	public List<Permission> findByRoleId(Integer roleId) {
		String querySql = "select t2.* from t_role_permission t1 , t_permission t2 where t1.role_id = @roleid and t1.permission_id = t2.id";
		Sql sql = Sqls.fetchString(querySql);
		sql.setParam("roleid", roleId);
		return NutzSqlUtil.getEntities(sql, dao, Permission.class);
	}

	public int deleteByIds(String[] ids) {
		Criteria cri = Cnd.cri();
		cri.where().andIn("id", ids);
		dao.clear(Permission.class, cri);
		return 1;
	}

	public int deleteByRoleId(Integer roleId) {
		String delSql = "delete from t_role_permission where role_id = @roleid";
		Sql sql = Sqls.fetchString(delSql);
		sql.setParam("roleid", roleId);
		dao.execute(sql);
		return 1;
	}

	public int savePermissionsWithRoleId(Integer roleId, String[] ids) {
		String iSql = "insert into t_role_permission values(@roleid,@permissionid)";
		Sql sql = Sqls.fetchString(iSql);
		for (String permissionid : ids) {
			sql.setParam("roleid", roleId);
			sql.setParam("permissionid", permissionid);
			sql.addBatch();
		}
		dao.execute(sql);
		return 1;
	}

}
